import axios, { InternalAxiosRequestConfig, AxiosResponse } from 'axios'

import { useUserStoreHook } from '@/store/modules/user'
import { ResultEnum } from '@/enums/ResultEnum'
import { TOKEN_KEY } from '@/enums/CacheEnum'

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' },
})

// 添加请求拦截器
service.interceptors.request.use(
  function (config: InternalAxiosRequestConfig) {
    const accessToken = localStorage.getItem(TOKEN_KEY)
    if (accessToken) {
      config.headers.Authorization = accessToken
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  },
)

// 添加响应拦截器
service.interceptors.response.use(
  function (response: AxiosResponse) {
    // 二进制数据则直接返回
    if (
      response.request.responseType === 'blob' ||
      response.request.responseType === 'arraybuffer'
    ) {
      return response.data
    }

    const { code, data, msg } = response.data
    if (code === ResultEnum.SUCCESS) {
      return data
    }

    ElMessage.error(msg || '系统出错')
    return Promise.reject(new Error(msg || 'Error'))
  },
  function (error) {
    const { code, msg } = error.response.data
    if (code === ResultEnum.TOKEN_INVALID) {
      ElMessageBox.confirm('当前页面已失效，请重新登录', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const userStore = useUserStoreHook()
        userStore.resetToken().then(() => {
          location.reload()
        })
      })
    } else {
      ElMessage.error(msg || '系统出错')
    }
    return Promise.reject(error.message)
  },
)

// 导出 axios 实例
export default service
